<template>
  <div>
    <div class="search">
      <SearchVue :searchType="searchType" @getSearchData="getSearchData"></SearchVue>
    </div>
    <!-- <div class="headeButton">
      <el-button type="primary" @click="addFn">添加内容</el-button>
    </div> -->
    <div class="draggable" style="padding: 20px">
      <el-table row-key="id" :data="tableData" style="width: 100%">
        <template v-for="(item, index) in oldList" :key="`col_${index}`">
          <el-table-column
            v-if="item.type == 1"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 2"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-button type="primary" size="small" @click="copyFn(scope.row)"
                  >复制编号</el-button
                >
                <el-button type="primary" size="small" @click="detilsFn(scope.row)">详情</el-button>
                <el-button type="warning" size="small" @click="changeTableFn(scope.row)"
                  >修改</el-button
                >
                <el-popconfirm title="是否确认删除" @confirm="confirmDeleteFn(scope.row)">
                  <template #reference>
                    <el-button type="danger" size="small"> 删除 </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 3"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row.image" />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        :current-page="pageData.page"
        :page-size="pageData.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      @close="closeFn"
      v-model="dialogVisibleAdd"
      title="添加"
      width="500"
      :before-close="dialogBeforeCloseFn"
    >
      <div>
        <el-form
          ref="formAddRef"
          :rules="rules"
          :model="formAdd"
          label-width="auto"
          style="max-width: 800px"
        >
          <el-form-item label="客服编号" prop="customerService">
            <el-input v-model="formAdd.customerService" class="imputeWidth" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="质保批号：" prop="filmNo">
            <el-input v-model="formAdd.filmNo" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="收货地址：" prop="region">
            <el-input v-model="formAdd.region" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="产品类型：" prop="filmType">
            <el-select
              @change="getFilmList"
              v-model="formAdd.filmType"
              placeholder="请选择产品类型"
            >
              <el-option
                v-for="item in optionsFilmType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品名称：" prop="filmId">
            <el-select
              @change="selectFilmName"
              v-model="formAdd.filmId"
              placeholder="请选择产品名称"
            >
              <el-option
                v-for="item in serFilmNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品批号：" prop="SerialNumber">
            <el-input v-model="formAdd.SerialNumber" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="质保年限：" prop="filmAge">
            <el-input v-model="formAdd.filmAge" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="漆面膜次数：" prop="lacquerNumber">
            <el-input v-model="formAdd.lacquerNumber" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="车顶膜次数：" prop="roofNumber">
            <el-input v-model="formAdd.roofNumber" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="太阳膜次数：" prop="sunNumber">
            <el-input v-model="formAdd.sunNumber" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="改色膜次数" prop="colorAlterationNumber">
            <el-input
              v-model="formAdd.colorAlterationNumber"
              class="imputeWidth"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="总贴膜次数" prop="count">
            <el-input v-model="formAdd.count" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="confirmFn(0)"> 确定 </el-button>
          <el-button @click="confirmFn(1)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-model="dialogVisibleDetils" title="详情" width="450">
      <div>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>产品信息</span>
            </div>
          </template>
          <div>产品型号：{{ detilsData.filmType }}</div>
          <div>产品类型：{{ detilsData.filmName }}</div>
          <div>质保年限：{{ detilsData.filmAge }}</div>
          <div>质保批号：{{ detilsData.filmNo }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>门店信息</span>
            </div>
          </template>
          <div>收货门店：{{ detilsData.storeName }}</div>
          <div>收货手机号：{{ detilsData.storePhone }}</div>
          <div>收货人：{{ detilsData.linkman }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>发货信息</span>
            </div>
          </template>
          <div v-if="!detilsData.customerService">发货门店：{{ detilsData.deliverStoreName }}</div>
          <div v-else>发货客服：{{ detilsData.customerService }}</div>
          <div>发货手机号：{{ detilsData.deliverStorePhone }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>待使用膜信息</span>
            </div>
          </template>
          <div>总次数：{{ detilsData.count }}</div>
          <div>漆面膜：{{ detilsData.lacquerNumber }}</div>
          <div>改色膜：{{ detilsData.colorAlterationNumber }}</div>
          <div>太阳膜：{{ detilsData.sunNumber }}</div>
          <div>车顶膜：{{ detilsData.roofNumber }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>已使用膜信息</span>
            </div>
          </template>
          <div>总次数：{{ detilsData.useCount }}</div>
          <div>漆面膜：{{ detilsData.uselacquerNumber }}</div>
          <div>改色膜：{{ detilsData.usecolorAlterationNumber }}</div>
          <div>太阳膜：{{ detilsData.usesunNumber }}</div>
          <div>车顶膜：{{ detilsData.useroofNumber }}</div>
        </el-card>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisibleImage">
      <div style="width: 100%; height: 100%">
        <img
          style="width: 100%; height: 100%"
          w-full
          :src="dialogVisibleImageUrl"
          alt="Preview Image"
        />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup >
import { userListAdd, } from '@/http/api/users.js'
import { deliverList, deliverListDelete, deliverListSerach, deliverListChange } from '@/http/api/deliver.js'
import { onMounted, reactive, ref, defineExpose } from 'vue'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import { baseURL } from '@/http/request.js'
import { ElMessage } from 'element-plus'
import SearchVue from '@/components/search/index.vue'
import { filmListSelect } from '@/http/api/film.js'
import dayjs from 'dayjs'
// 只适合做平级的table行和列拖动

let baseURL2 = baseURL
const oldList = ref()
const newList = ref()
let serFilmNameList = ref([])
let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]
// 表头
const tableItems = ref([
  {
    label: '型号',
    prop: 'filmName',
    type: 1
  }, {
    label: '类型',
    prop: 'filmType',
    type: 1
  },
  {
    label: '质保年限',
    prop: 'filmAge',
    type: 1
  }, {
    label: '质保批号',
    prop: 'filmNo',
    type: 1
  }, {
    label: '收货门店',
    prop: 'storeName',
    type: 1
  }, {
    label: '收货手机号',
    prop: 'storePhone',
    type: 1
  }, {
    label: '收货人',
    prop: 'linkman',
    type: 1
  },
  {
    label: '发货时间',
    prop: 'create_time',
    type: 1
  },
  {
    label: '操作',
    prop: 'age',
    type: 2
  },
])
// 表体数据
let tableData = ref([])
let searchType = ref([
  {
    title: '收货状态：',
    type: 3,
    model: 'deliverStatus',
    hint: '请选择',
    options: [
      {
        label: '待签收',
        value: 0
      }, {
        label: '已签收',
        value: 1
      }, {
        label: '拒收',
        value: 2
      },
    ]
  }, {
    title: '收货门店：',
    type: 1,
    model: 'storeName',
    hint: '请输入收货门店'
  }, {
    title: '收货人：',
    type: 1,
    model: 'linkman',
    hint: '请输入收货人'
  }, {
    title: '质保批号：',
    type: 1,
    model: 'filmNo',
    hint: '请输入质保批号'
  }, {
    title: '型号：',
    type: 1,
    model: 'filmName',
    hint: '请输入型号'
  }, {
    title: '类型：',
    type: 1,
    model: 'filmType',
    hint: '请输入类型'
  },
])
let formAdd = reactive({})
let image = ref([])
let dialogVisibleImage = ref(false)
let searchData = reactive({})
let pageData = reactive({
  page: 1,
  size: 10
})
// 修改选择后重新获取膜列表
const getFilmList = async () => {
  let serchFilm = {
    storeId: formAdd.storeId,
    filmType: formAdd.filmType
  }
  const res = await filmListSelect(serchFilm)
  serFilmNameList.value = res.data.res.map((item) => {
    return {
      value: item.id,
      label: item.name,
      ...item
    }
  })
}
const getData = async () => {
  let deliverStatus = []
  if (!Array.isArray(searchData.deliverStatus) && typeof (searchData.deliverStatus) == 'number') {
    deliverStatus = [searchData.deliverStatus]
  }
  let data = {
    ...pageData,
    ...searchData,
    deliverStatus
  }
  const res = await deliverListSerach(data)
  tableData.value = res.data.res.map((item) => {
    return {
      ...item,
      statusSize: item.status === '0' ? '待审核' : item.status === '1' ? '审核通过' : '已驳回',
      create_time: dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss')
    }
  })
  total.value = res.data.total
}
let dialogVisibleAdd = ref(false)
let total = ref(0)
const addFn = () => {
  dialogVisibleAdd.value = true
}
const closeFn = () => {
  dialogVisibleAdd.value = false
}

const rules = reactive({
  filmNo: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  customerService: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  SerialNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], region: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmType: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmId: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmAge: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], lacquerNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], roofNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], sunNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], colorAlterationNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], count: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
})
// 上传成功
const handSuccessFn = (data) => {
  formAdd.avatar = data.image_url
}
let formAddRef = ref()
// 点击添加或这修改按钮
const confirmFn = async (number) => {
  if (number == 0) {
    await formAddRef.value.validate(async (valid, fields) => {
      console.log(valid)
      if (valid) {
        try {
          if (!formAdd.id) {
            await userListAdd(formAdd)
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            delete formAdd.statusSize
            delete formAdd.workTime
            delete formAdd.create_time
            console.log(formAdd)
            let allCount = formAdd.lacquerNumber * 1 + formAdd.roofNumber * 1 + formAdd.sunNumber * 1 + formAdd.colorAlterationNumber * 1
            try {
              if (formAdd.count * 1 < allCount) {
                throw '不能大于总次数'
              }
              const res = await deliverListChange(formAdd)
              ElMessage({
                message: res.data.message,
                type: 'success',
              })
            } catch (error) {
              ElMessage({
                message: error,
                type: 'error',
              })
            }
          }
          getData()

        } catch (error) {
          ElMessage({
            message: '失败',
            type: 'error',
          })
        }


      } else {
        ElMessage({
          message: '请补充完整信息',
          type: 'error',
        })
      }
    })
  }
  formAdd = reactive({})
  image.value = []
  dialogVisibleAdd.value = false
}
// 关闭弹窗
const dialogBeforeCloseFn = () => {
  formAdd = reactive({})
  image.value = []
  dialogVisibleAdd.value = false
}
// 修改size
const handleSizeChange = (data) => {
  pageData.size = data
  getData()
}
// 修改页数
const handleCurrentChange = (data) => {
  pageData.page = data
  getData()
}
// 确定删除
const confirmDeleteFn = async (data) => {
  try {
    const res = await deliverListDelete({ id: data.id })
    ElMessage({
      message: res.data.message,
      type: 'success',
    })
    getData()
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }

}
// 修改
const changeTableFn = (data) => {
  dialogVisibleAdd.value = true
  Object.assign(formAdd, data)
  getFilmList()
}
const getSearchData = async (data) => {
  searchData = data
  getData()
  // let dataS = {
  //   ...data,
  //   ...pageData
  // }
  // let res = await qualitySerach(dataS)
  // tableData.value = res.data.res.map((item) => {
  //   return {
  //     ...item,
  //   }
  // })
  // total.value = res.data.total
}
const handlePictureCardPreview = (data) => {
  dialogVisibleImage.value = true
}
let dialogVisibleDetils = ref(false)
let detilsData = reactive({})
// 查看详情
const detilsFn = (data) => {
  dialogVisibleDetils.value = true
  Object.assign(detilsData, data)
}
// 复制
const copyFn = async (data) => {
  console.log(data)
  try {
    await navigator.clipboard.writeText(data.filmNo)
    ElMessage({
      message: '复制成功',
      type: 'success',
    })
  } catch (err) {

  }
}
// 审核通过
const autionFn = async (num) => {
  dialogVisibleDetils.value = false
}
let inputFile = ref(null)
// 上传图片
const upImgFn = (data, index) => {
  inputFile.value[0].addEventListener('change', async function (event) {
    var files = event.target.files[0]
    const formData = new FormData()
    //files 文件信息
    formData.append("uploadFiles", files)
    //提交的其他字段
    // 发送ajax请求
    const res = await uploadAvatar(formData)
    data.image = res.data.image_url

  })
  // 将input添加到文档中
  // document.body.appendChild(input);
  inputFile.value[0].click()
}
const deleteImgFn = (data) => {
  data.image = ''
}
let dialogVisibleImageUrl = ref('')
const magnifyFn = (data) => {
  dialogVisibleImage.value = true
  dialogVisibleImageUrl.value = data.image
}
onMounted(() => {
  oldList.value = JSON.parse(JSON.stringify(tableItems.value))
  newList.value = JSON.parse(JSON.stringify(tableItems.value))
  getData()
})
defineExpose({ getData })
</script>
<style lang="scss" scoped>
.imputeWidth {
  width: 260px;
}
.imageList {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.imageTitleBox {
  padding: 10px 0;
}
.imageBox {
  width: 134px;
  height: 135px;
  img {
    width: 100%;
    height: 100%;
  }
}
.imageTitle {
  width: 134px;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 使用省略号表示文本溢出 */
}
.card {
  margin-top: 20px;
}
.imagebOx {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.imageBoxTitle {
  width: 150px;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 使用省略号表示文本溢出 */
  text-align: center;
}
.upImg {
  background: #3c3c3c;
  width: 180px;
  height: 180px;
  border-radius: 20px;
  font-size: 50px;
  cursor: pointer;
}

.imgBox {
  width: 180px;
  height: 180px;
  border-radius: 20px;
  position: relative;
  left: 0;
  top: 0;
  img {
    width: 100%;
    height: 100%;
  }
  .Mask {
    flex-wrap: wrap;
    background: black;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    justify-content: space-around;
    font-size: 30px;
  }
  .Mask:hover {
    opacity: 0.6;
  }
  cursor: pointer;
}
</style>